<script setup>
  const emit = defineEmits(['success'])
  import { uploadFile } from '@/api/file'
  import { ref } from 'vue'
  function handleClick() {
    // 1. 创建input元素
    const input = document.createElement('input')
    // 2. 设置input属性
    input.type = 'file'
    input.accept = 'image/*'
    input.multiple = true
    // 4. 触发input点击事件
    input.click()
    input.onchange = async function () {
      const files = this.files
      for (let i = 0; i < files.length; i++) {
        const res = await uploadFile(files[i], 'image')
        if (res.data.isRepeated) {
          ElMessage.warning('图片已存在')
          continue
        }
        emit('success', res.data)
      }
    }
  }
  const darg = ref(false)
  function handleDargEneter(e) {
    darg.value = true
    e.stopPropagation()
    e.preventDefault()
  }
  function handleDargOver(e) {
    darg.value = true
    e.stopPropagation()
    e.preventDefault()
  }
  function handleDropLeave(e) {
    darg.value = false
    e.stopPropagation()
    e.preventDefault()
  }
  async function handleDrop(e) {
    darg.value = false
    e.stopPropagation()
    e.preventDefault()
    const data = e.dataTransfer
    const files = data.files
    for (let i = 0; i < files.length; i++) {
      const res = await uploadFile(files[i], 'image')
      if (res.data.isRepeated) {
        ElMessage.warning('图片已存在')
        continue
      }
      emit('success', res.data)
    }
  }
</script>
<template>
  <div
    class="upload flex-center"
    @click="handleClick"
    @drop="handleDrop"
    @dragenter="handleDargEneter"
    @dragover="handleDargOver"
    @dragleave="handleDropLeave"
    :class="{ darg }"
  >
    <div>
      <svg class="icon" aria-hidden="true">
        <use xlink:href="#icon-cloudupload-fill"></use>
      </svg>
    </div>
    <div>拖拽上传</div>
  </div>
</template>
<style lang="scss" scoped>
  .upload {
    flex-direction: column;
    width: 100%;
    height: 100%;
    border: 1px dashed var(--color-border);
    border-radius: 10px;
    cursor: pointer;
    &:hover {
      border-color: var(--color-border-hover);
    }
    &.darg {
      border-color: var(--color-border-hover);
    }
  }
</style>
